import { useEffect, useRef, useState } from "react";
import { Editor, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";

import "./iconfont.scss";
import './userReadme.scss'
import { EAXMINE_NOTICE_ID, RESPONSE_CODE, STORE_KEY } from "@/common/config";
import { IUserProfileEditPromise, USER_PROFILE_STATUS } from "@/typing";
import { handleInitStoreBaseInfo, handleLoginCallback, showToast, subscribeMessage } from "@/common/util";
import useProfileInfoAction from "@/hooks/useProfileInfoAction";
import useProfileStatusAction from "@/hooks/useProfileStatusAction";



const EditorPage = () => {
  const [formats, setFormats] = useState<any>({});

  const defaultPlaceholder = '可用几段话简要描述你的职业，人生履历，擅长分享的知识经验，兴趣爱好，特长等。'
  const [editorHeight, setEditorHeight] = useState(300)
  const { handleShopUserprofileEdit } = useProfileInfoAction()
  const { handleInitProfileStatusPromise } = useProfileStatusAction()

  const [textChanged, setTextChanged] = useState(false)
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const [isIOS, setIsIOS] = useState(false);
  const editorCtxRef = useRef<any>(null);
  const [readMe, setReadMe] = useState("");
  const [readMeText, setReadMeText] = useState("");

  const [refresh, setRefresh] = useState(0);





  const onEditorReady = () => {
    // 富文本内容回显

    Taro.createSelectorQuery().select("#editor").context((res) => {
      const storeReadMe = Taro.getStorageSync(STORE_KEY.README)
      editorCtxRef.current = res.context;
      console.log(editorCtxRef.current)
      console.log(storeReadMe)
      editorCtxRef.current.setContents({
        html: storeReadMe,
      })
    }).exec();
  };



  const format = (e) => {

    const { name, value } = e.target.dataset;
    if (!name) return;
    editorCtxRef.current.format(name, value);
  };

  const onInput = (e) => {
    console.log(e.detail.text)
    setReadMe(e.detail.html);
    setReadMeText(e.detail.text)
    // setValue(convertHtmlToNodes(e.detail.html));
    // setValue(Taro.parseHtml(e.detail.html));
    setRefresh(refresh + 1);
    // Taro.setStorageSync(STORE_KEY.README, readMeText)

  };

  const onStatusChange = (e) => {
    // console.log("----------change--------------");
    const formats = e.detail;
    setFormats(formats);
  };


  const handleUpdatePosition = (keyboardHeight) => {
    const toolbarHeight = 50
    const { windowHeight } = Taro.getSystemInfoSync()
    let editorH = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    setEditorHeight(editorH)
    setKeyboardHeight(keyboardHeight);
  }
  const handleInitPage = () => {
    const platform = Taro.getSystemInfoSync().platform
    const isIOS = platform === 'ios'

    setIsIOS(isIOS)

    handleUpdatePosition(0)
    let keyboardHeight = 0
    Taro.onKeyboardHeightChange((res: any) => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        Taro.pageScrollTo({
          scrollTop: 0,
          success() {
            handleUpdatePosition(keyboardHeight)
            editorCtxRef.current.scrollIntoView()
          }
        })
      }, duration)

    })
  }
  const handleSaveReadMe = async () => {
    handleInitProfileStatusPromise().then(res => {
      if (res.code === RESPONSE_CODE.SUCCESS) {
        const status = res.data.status;

        if (status === USER_PROFILE_STATUS.enable) {
          if (readMe === '') {
            Taro.navigateBack()
          } else if (readMe && textChanged) {
            Taro.showModal({
              title: '提示',
              content: '确定修改自述吗？',
              success: async function (res) {
                if (res.confirm) {
                  const editRes = await handleShopUserprofileEdit({ readme: readMe }) as IUserProfileEditPromise
                  Taro.hideLoading({

                  })
                  const { code, msg } = editRes
                  if (code === RESPONSE_CODE.SUCCESS) {
                    showToast(msg)
                    const storeBaseUserInfo = handleInitStoreBaseInfo()
                    storeBaseUserInfo['modify_field']['readme'] = USER_PROFILE_STATUS.disable
                    Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
                   
                    subscribeMessage([EAXMINE_NOTICE_ID]).then(()=>{
                    
                      Taro.navigateBack();
                  })


                  } else if (code === RESPONSE_CODE.LOGIN_EXPIRE || code === RESPONSE_CODE.LOGIN_NEED) {
                    handleLoginCallback(() => handleSaveReadMe())
                    //  Taro.removeStorageSync(STORE_KEY.PHONE)
                    // await handleInitLogin().then(async () => {
                    //   handleSaveReadMe()
                    // })
                  } else {
                    showToast(msg)
                  }
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })

          }

        }
        else{
             Taro.setStorageSync(STORE_KEY.README, readMe)
          }
      } else if (res.code === RESPONSE_CODE.LOGIN_EXPIRE || res.code === RESPONSE_CODE.LOGIN_NEED) {
        handleLoginCallback(() => handleSaveReadMe())
      }
    })
   
  }
  useEffect(() => {
    setTextChanged(true)

  }, [readMe]);
  useEffect(() => {

    handleInitPage()
  }, []);
  return (
    <View className="w-full h-100vh box-border p-32px">
      <Editor
        id="editor"
        className="ql-container"
        placeholder={defaultPlaceholder}
        onStatusChange={onStatusChange}

        onInput={onInput}
        onReady={onEditorReady} // 编辑器初始化完成时触发
      />
      {keyboardHeight > 0 && <View className="toolbar" style={{ bottom: isIOS ? keyboardHeight : 0 + 'px' }} >

        <View>
          <Text
            className={`iconfont icon-zitijiacu ${formats.bold ? "ql-active" : ""}`}
            data-name="bold"
            onClick={format}
          ></Text>

        </View>
        <View className="bg-#0A0A0A w-136px h-82px text-#fff flex items-center justify-center text-32px" onClick={handleSaveReadMe}>保存</View>

      </View>}
      {/* <View className="bg-#0A0A0A w-136px h-82px text-#fff flex items-center justify-center text-32px" onClick={handleSaveReadMe}>保存</View> */}
    </View>
  );
};

export default EditorPage;
